package com.mjfeed.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mjfeed.Constants;
import com.mjfeed.dao.ProductCategoryDao;
import com.mjfeed.entity.ProductCategory;
import com.mjfeed.service.ProductCategoryService;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;
import com.mjfeed.util.QueryCondition;

@Service("productCategoryService")
public class ProductCategoryServiceImpl extends BaseServiceImpl implements ProductCategoryService {
	@Resource(name="productCategoryDao")
	private ProductCategoryDao productCategoryDao;
	
	@Transactional(readOnly = true)
	public Pagination<ProductCategory> getPagination(ParamBean paramBean) {
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		if (StringUtils.isNotBlank(paramBean.getKeyword())) {
			String field = (paramBean.getField() == null) ? "name" : paramBean.getField();
			queryConditions.add(new QueryCondition(field, QueryCondition.LK, paramBean.getKeyword()));
		}
		String orderBy = "order by orders asc";
		Pagination<ProductCategory> pagination = (Pagination<ProductCategory>)getPagination(ProductCategory.class, queryConditions, orderBy, paramBean.getPage(), paramBean.getPageSize());
		pagination.setPageHtml(paramBean.getUrl());
		pagination.setRecordList(productCategoryDao.sort(pagination.getRecordList(), null));
		return pagination;
	}

	@Transactional(readOnly = true)
	public List<ProductCategory> findTree() {
		return productCategoryDao.findChildren(null, null);
	}

	@Transactional(readOnly = true)
	public List<ProductCategory> findRoots() {
		return productCategoryDao.findRoots(null);
	}
	
	public void build(ProductCategory productCategory) {
		MultipartFile multipartFile = productCategory.getFile();
		if (multipartFile != null && !multipartFile.isEmpty()) {
			try {
				String uploadPath = Constants.UPLOAD_PATH_PREFIX_PRODUCTCATEGORY + DateFormatUtils.format(new Date(), "yyyyMMdd")+"/";
				String uuid = UUID.randomUUID().toString();
				String sourcePath = uploadPath + uuid + FilenameUtils.EXTENSION_SEPARATOR + FilenameUtils.getExtension(multipartFile.getOriginalFilename());

				File sourceFile = new File(sourcePath);
				if (!sourceFile.getParentFile().exists()) {
					sourceFile.getParentFile().mkdirs();
				}
				multipartFile.transferTo(sourceFile);
				productCategory.setSource(sourcePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
